const cartModel = require('../models/cartModel');
const { success, badRequest, notFound } = require('../utils/response');

const getCart = async (req, res) => {
  try {
    const cartItems = await cartModel.getCartByUserId(req.userId);
    success(res, cartItems);
  } catch (err) {
    notFound(res, 'Cart not found');
  }
};

const addItemToCart = async (req, res) => {
  try {
    const { productId, quantity } = req.body;
    if (!productId || !quantity) {
      return badRequest(res, 'Product ID and quantity are required');
    }
    
    const cartItems = await cartModel.addToCart(req.userId, productId, quantity);
    success(res, cartItems, 'Item added to cart');
  } catch (err) {
    badRequest(res, 'Failed to add item to cart');
  }
};

const updateCartItem = async (req, res) => {
  try {
    const { productId } = req.params;
    const { quantity } = req.body;
    
    if (!quantity) {
      return badRequest(res, 'Quantity is required');
    }
    
    const cartItems = await cartModel.updateCartItem(req.userId, productId, quantity);
    success(res, cartItems, 'Cart item updated');
  } catch (err) {
    badRequest(res, 'Failed to update cart item');
  }
};

const removeCartItem = async (req, res) => {
  try {
    const { productId } = req.params;
    const cartItems = await cartModel.removeFromCart(req.userId, productId);
    success(res, cartItems, 'Item removed from cart');
  } catch (err) {
    badRequest(res, 'Failed to remove item from cart');
  }
};

module.exports = {
  getCart,
  addItemToCart,
  updateCartItem,
  removeCartItem
};